<!DOCTYPE HTML>
<html lang="en">
<head>
<title>OnError() - Syntax &amp; Usage | AutoHotkey</title>
<meta name="description" content="The OnError function specifies a function to run automatically when an unhandled error occurs." />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link href="../static/theme.css" rel="stylesheet" type="text/css" />
<script src="../static/content.js" type="text/javascript"></script>
</head>
<body>

<h1>OnError() <span class="ver">[v1.1.29+]</span></h1>
<p>Specifies a <a href="../Functions.htm">function</a> to run automatically when an unhandled error occurs.</p>

<pre class="Syntax"><span class="func">OnError</span>(Func <span class="optional">, AddRemove</span>)</pre>

<h2>Parameters</h2>
<dl>

  <dt>Func</dt>
  <dd><p>A function name or <a href="../objects/Functor.htm">function object</a> to call when an unhandled error occurs. The function is given the exception object as a parameter, and may return a non-zero integer to block the default error dialog.</p></dd>
  
  <dt>AddRemove</dt>
  <dd><p>One of the following values:<br>
  <strong>1</strong> (the default): Call the function after any previously registered functions.<br>
  <strong>-1</strong>: Call the function before any previously registered functions.<br>
  <strong>0</strong>: Do not call the function.</p>
  </dd>

</dl>

<h2>Remarks</h2>
<p><em>Func</em> is called only for errors or exceptions which would normally cause an error message to be displayed. It cannot be called for a load-time error, since OnError cannot be called until after the script has loaded.</p>
<p>If any error function returns a non-zero integer, the thread exits. If an error occurs (or an exception is thrown) within an error function, an error message is displayed for the new error and the thread exits. Otherwise, all error function are called, an error message is displayed and the thread exits.</p>
<p><em>Func</em>'s first parameter receives the thrown value or <a href="Throw.htm#Exception">Exception</a> object. If this is an object, it can be modified to affect what the default error dialog displays.</p>
<p><em>Func</em> is called on the current <a href="../misc/Threads.htm">thread</a>, before it exits (that is, before the call stack unwinds).</p>

<h2>Related</h2>
<p><a href="Try.htm">Try</a>, <a href="Catch.htm">Catch</a>, <a href="Throw.htm">Throw</a>, <a href="OnExit.htm">OnExit</a></p>

<h2 id="Examples">Examples</h2>
<div class="ex" id="ExBasic">
<p><a href="#ExBasic">#1</a></p>
<pre>
OnError("LogError")
%cause% := error

LogError(exception) {
    FileAppend % "Error on line " exception.Line ": " exception.Message "`n"
        , errorlog.txt
    return true
}
</pre>
</div>

</body>
</html>
